//index.js
const EventEmitter = require('../../common/EventEmitter');
const User = require('../../common/user');
const requester = require('../../common/requester');
const $$onLoad = require('../../appLoaded/onLoad');
const fans = require('../../utils/fans.js');
const app = getApp();

Page({
    data: {
        deviceInfo: {
            windowHeight: ''
        },
        userInfo: {},
        actions: ['goVideoList'],
        imageList: '',
        isRefreshing: false,
        isAudit: true,
        isAuthed: true
    },

    onLoad: function (param) {
        $$onLoad()
            .then(() => {
                let isAudit = app.globalData.isAudit,
                    isAuthed = app.globalData.isAuthed;

                this.setData({
                    isAudit,
                    isAuthed,
                    id: param.id
                });

                if (isAuthed) {
                    this.init(param);
                }
            });
    },

    onReady: function (res) {
        this.videoContext = wx.createVideoContext('myVideo')
    },

    init: function (param) {
        let id = param && param.id || this.data.id;
        this.queryVideoDetail(id);
        this.getRecommendVideoRes(id);
        this.setData({
            isAuthed: true,
        });
        EventEmitter.addListener('backFormComment', () => {
            this.queryVideoDetail(id);
        });
    },

    queryVideoDetail: function (id) {
        return requester.request({
            url: requester.service.queryVideoDetail,
            data: {
                resourceId: id
            }
        }).then(res => {
            this.setData({
                video: res.data,
                userId: res.data.userVo.userId,
                commentList: res.data.partCommentList,
                isLiked: +res.data.isLiked,
                likeCount: res.data.likeCount,
                isFollowed:res.data.userVo.isFollowed
            })
        });
    },

    getRecommendVideoRes: function (id) {
        return requester.request({
            url: requester.service.recommendVideoRes,
            data: {
                resourceId: id
            }
        }).then(res => {
            let video = res.data.simpleVideoResourceVos;
            this.setData({
                videoSource: video
            });
        });
    },

    authComment: function (res) {
        if (res.detail.iv) {
            User.saveUserInfo(res.detail.userInfo)
                .then(() => {
                    console.log('authed');
                    this.goComment();
                });
        } else {
            wx.showToast({
                title: '请先允许授权',
                icon: 'none',
                duration: 1000
            })
        }
    },
    /**
     * 进入评论列表页面。
     */
    goComment: function () {
        let id = this.data.id;
        wx.navigateTo({
            url: "../comment/comment?id=comment&resourceId=" + id
        });
    },

    back: function () {
        wx.redirectTo({
            url: '../videoList/videoList'
        });
    },

    authLike: function (res) {
        if (res.detail.iv) {
            User.saveUserInfo(res.detail.userInfo)
                .then(() => {
                    this.likeTap();
                });
        } else {
            wx.showToast({
                title: '请先允许授权',
                icon: 'none',
                duration: 1000
            })
        }
    },
    /**
     * 点赞
     */
    likeTap: function () {
        let id = this.data.id;
        let liked = this.data.isLiked;
        let likeCount = this.data.likeCount;
        let me = this;

        let resCount = isNaN(likeCount)
            ? likeCount
            : liked ?
                +likeCount - 1
                : +likeCount + 1;

        me.setData({
            isLiked: !liked,
            likeCount: resCount
        });

        requester.request({
            url: !liked ? requester.service.favorComment : requester.service.cancelImageLike,
            data: {
                resourceId: id,
                commentType: 1,
                content: ''
            }
        })
    },

    onVideoEnd: function (e) {
        this.videoContext.exitFullScreen();
    },

    downloadVideo: function (e) {
        wx.showModal({
            title: '提示',
            content: '分享给好友后即可下载哦~',
            confirmText: '分享下载',
            success: (res) => {
                if (res.confirm) {
                    this.shareAndDownload();
                } else if (res.cancel) {
                    console.log('已取消')
                }
            }
        })
    },

    shareAndDownload:function () {
        this.showShareMenu()
            .then(res=>{
                console.log(res);
                console.log("分享成功");
            })
    },

    showShareMenu: function () {
        return new Promise((resolve, reject) => {
            wx.showShareMenu({
                withShareTicket: true,
                success: resolve,
                fail: reject
            })
        })
    },

    // 进入用户详情页面
    goUserDetail: function (e) {
        if(this.data.isAudit){
            return
        }
        let userId = e.currentTarget.dataset.userId;
        wx.redirectTo({
            url: `../thirdUser/thirdUser?userId=${userId}`
        });
    },

    follow: function () {
        let id = this.data.userId;
        let me = this;
        fans.follow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '关注成功'
                    });
                    me.setData({
                        isFollowed: 1
                    })
                }
            })
    },
    unfollow: function () {
        let id = this.data.userId;
        let me = this;
        fans.unfollow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '已取消关注'
                    });
                    me.setData({
                        isFollowed: 0
                    })
                }
            })
    },

    onShareAppMessage: function () {
        return {
            title: this.data.video.textInfo,
            path: '/pages/videoDetail/videoDetail?id=' + this.data.id,
            imageUrl: this.data.video.smallPicUrl,
            success: function (res) {
                // 转发成功
                wx.showToast({
                    title: '分享成功',
                    icon: 'success',
                    duration: 1000
                })
            },
            fail: function (res) {
                // 转发失败
                wx.showToast({
                    title: '分享失败',
                    icon: 'none',
                    duration: 1000
                })
            }
        }
    }
});
